<!-- 用户管理 -->
<template>
  <div class='userManagement_container main_container'>
    <div style="height: 100%" class="userManagement_box">

      <div class="search_form_box">
        <el-button @click="addShow" type="primary" size="mini">新增用户</el-button>
      </div>

      <div class="table_box">
        <materialTable ref="multipleTable" :tableHead="tableHead" :tableData="tableData" ></materialTable>
      </div>

      <div>
        <pagination :tablePage="tablePage"></pagination>
      </div>


    </div>

    <el-dialog @open="openDialog" :close-on-click-modal="false" :title="dialog.title" custom-class="add_dialog" :visible.sync="dialog.show">
      <div v-if="dialog.title=='新增用户'||dialog.title=='编辑用户'">
        <el-form ref="addForm" :rules="rules" :model="addForm"  label-position="right">
          <!-- <form-item 
            label="姓名"  
            model="username" 
            type="input"
            :disabled="dialog.title=='编辑用户'"
            :addForm="addForm"
          ></form-item> -->
          <form-item 
            label="姓名"  
            model="realname" 
            type="input"
            :addForm="addForm"
          ></form-item>
          <form-item 
            label="手机号"
            model="mobile" 
            type="input"
            maxlength="11"
            :addForm="addForm"
          ></form-item>
          <form-item 
            label="密码"  
            model="password" 
            type="input"
            v-if="dialog.title == '新增用户'"
            showPassword
            :addForm="addForm"
          ></form-item>
          <form-item 
            label="确认密码"  
            model="passwordCopy" 
            v-if="dialog.title == '新增用户'"
            type="input"
            showPassword
            :addForm="addForm"
          ></form-item>
          <form-item 
            label="性别"  
            model="gender" 
            type="radio"
            :radioList="radioList"
            :addForm="addForm"
          ></form-item>
          <form-item 
            label="邮箱"  
            model="email" 
            type="input"
            :disabled="dialog.title=='查看用户'"
            :addForm="addForm"
          ></form-item>

          <el-form-item label="设置角色 : ">
            <el-checkbox-group v-model="addForm.roleIds" autocomplete="off" style="width:100%">
              <el-checkbox
                v-for="item in roleListData"
                :label="item.roleId"
                :key="item.roleId"
              >{{item.roleName}}</el-checkbox>
            </el-checkbox-group>
          </el-form-item>

          <form-item 
            label="用户类型"  
            model="userType" 
            type="radio"
            v-if="loginUserType == 1"
            :radioList="userTypeList"
            :addForm="addForm"
          ></form-item>
          <form-item 
            label="一级商家"  
            model="seniorId" 
            type="select"
            multiple
            :selectList="firstList"
            :selectOption="firstOption"
            :addForm="addForm"
          ></form-item>
          <form-item 
            label="主体商家"  
            model="subjectId" 
            type="select"
            multiple
            :selectList="mainList"
            :selectOption="mainOption"
            :addForm="addForm"
          ></form-item>
          <form-item 
            label="二级商家"  
            model="siteId" 
            type="select"
            multiple
            :selectList="secondList"
            :selectOption="secondOption"
            :addForm="addForm"
          ></form-item>
          <form-item 
            label="是否管理员"  
            model="isAdmin" 
            type="radio"
            v-if="isShowAdmin"
            :radioList="adminList"
            :addForm="addForm"
          ></form-item>
          
          
          
        </el-form>
      </div>

     


      <div v-if="dialog.title=='设置角色'">
        <el-form :model="setRole" label-position="left" ref="roleForm">
          <el-form-item label="设置角色 : ">
            <el-checkbox-group v-model="setRole.roleIds" autocomplete="off" style="width:100%">
              <el-checkbox
                v-for="item in roleListData"
                :label="item.roleId"
                :key="item.roleId"
              >{{item.roleName}}</el-checkbox>
            </el-checkbox-group>
          </el-form-item>
        </el-form>
      </div>


      <div slot="footer" class="dialog-footer">
        <el-button type="default" size="mini" @click="dialog.show = false">取 消</el-button>

        <el-button type="primary" :loading="btnLoading" size="mini" @click="setRoleSub" v-if="dialog.title=='设置角色'">确 定</el-button>
        <el-button type="primary" :loading="btnLoading" size="mini" @click="addSubmit" v-if="dialog.title=='新增用户'">确 定</el-button>
        <el-button type="primary" :loading="btnLoading" size="mini" @click="editSubmit" v-if="dialog.title=='编辑用户'">确 定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import materialTable from "@/components/assembly/materialTable";
import pagination from "@/components/assembly/pagination";
import organizationStructure from "@/components/assembly/organizationStructure";
import { createNamespacedHelpers } from "vuex";
let { mapActions } = createNamespacedHelpers("accountManagement");
let myVue = {};
let obj = {};

export default {
  name: 'accountManagement',
  data() {
    return {
      btnLoading: false,
      shakeId: 0,
      jwtAuth: {},
      loginIsAdmin: null,
      loginUserType: null,
      
     
      radioList: [
        { value: 1, label: '男' },
        { value: 0, label: '女' },
      ],
      adminList: [
        { value: 1, label: '是' },
        { value: 0, label: '否' },
      ],
      userTypeList: [
        { value: 1, label: '后端云平台管理员' },
        { value: 2, label: '公司用户' },
      ],

      firstList: [],
       firstOption: {
        label: 'seniorName',
        value: 'seniorId',
      },

      mainList: [],
      mainOption: {
        label: 'subjectName',
        value: 'subjectId',
      },
      
      secondList: [],
      secondOption: {
        label: 'siteName',
        value: 'siteId',
      },
      dialog: {
        title: "",
        show: false
      },

      tablePage: {
        curPage: 1,
        pageSize: 10,
        totalRows: 0,
      },
      tableHead: {
        // selection: {
        //   fun: this.handleSelectionChangeDelete
        // },
        // keyId: 'accountId',
        setFunction: [
          {
            fun: this.editShow,
            name: "编辑",
          },
          {
            fun: this.lockedFun,
            name: "禁用",
            hideKey: "locked",
            hideState: "0",
          },
          {
            fun: this.lockedFun,
            name: "启用",
            hideKey: "locked",
            hideState: "1",
          },
          {
            fun: this.resetPassword,
            name: "重置密码",
            hideKey: "locked",
            hideState: "0"
          },
          {
            fun: this.deleteShow,
            name: "删除",
          },
          {
            fun: this.setRoleShow,
            name: "设置角色",
            hideKey: "locked",
            hideState: "0",
          },
        ],
        noDataText: "暂无成员",
        data: [
          
          // {
          //   name: "登录名",
          //   key: "username",
          // },
          {
            name: "姓名",
            key: "realname",
          },
          {
            name: "手机号",
            key: "mobile",
          },
          {
            name: "角色",
            key: "roleStr",
          },
          {
            name: "二级商家",
            key: "siteName",
          },
          {
            name: "管理主体",
            key: "subjectName",
          },
          {
            name: "一级商家",
            key: "seniorName",
          },
          {
            name: "创建时间",
            key: "createTime",
          },
          {
            name: "修改时间",
            key: "updateTime",
          },
          
          
          
          {
            name: "账号状态",
            key: "locked",
            filter: {
              1: "禁用",
              0: "启用"
            }
          }
        ]
      },
      tableData: [],

      
      
      editForm: {
        organName: "",
        parent: []
      },
      
      adminCheck: false,
      ungroupActive: true,

      addForm: {
        // username: "",
        realname: "",
        isAdmin: 0,
        userType: 2,
        gender: '',
        mobile: "",
        email: "",
        roleIds: [],
      },
      roleListData: [],
      setRole: {
        roleIds: [],
        userId: ""
      },
      rules: {
        // username: [
        //   { required: true, message: '请输入姓名', trigger: 'change' }
        // ],
        realname: [
          { required: true, message: '请输入姓名', trigger: 'change' }
        ],
        gender: [
          { required: true, message: '请选择性别', trigger: 'change' }
        ],
        mobile: [
          { required: true, message: '请入手机号', trigger: 'change' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'change' },
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'change' }
        ],
        passwordCopy: [
          { required: true, message: '请再次输入密码', trigger: 'change' }
        ],
      },

    }
  },

  beforeCreate() {
    myVue = this;
  },

  computed: {
    isShowAdmin() {
      if(this.loginUserType == 1) {
        return true;
      }else if(this.loginUserType == 2) {
        if(this.loginIsAdmin == 1) {
          return true;
        }else {
          return false;
        }
      }
    }
  },

  created() {
    this.jwtAuth = JSON.parse(localStorage.getItem("jwtAuth"));
    console.log(this.jwtAuth)
    this.loginUserType = this.jwtAuth.userType
    this.loginIsAdmin = this.jwtAuth.extMap.isAdmin
    
    // console.log(this.loginUserType)
    // console.log(this.loginIsAdmin)

    this.initFirstList();
    this.initMainList();
    this.initSecondList();
    this.initRoleList();
    this.initData();

  },

  mounted() {
    
  },
  

  methods: {
    ...mapActions(["formGet", "post"]),

    initRoleList() {
      this.post({
        API: "roleList",
        data: {}
      }) .then(res => {
        this.roleListData = res;
      }) .catch(err => {
        this.$message.error(err);
      });
    },

    initFirstList() {
      this.post({
        API: 'firstList',
        data: {}
      }).then(res => {
        this.firstList = res;
      }).catch(err => {
        this.$message.error(err);
      })
    },
    initMainList() {
      this.post({
        API: 'mainList',
        data: {}
      }).then(res => {
        this.mainList = res;
      }).catch(err => {
        this.$message.error(err);
      })
    },
    initSecondList() {
      this.formGet({
        API: 'secondList',
        data: {}
      }).then(res => {
        this.secondList = res;
      }).catch(err => {
        this.$message.error(err);
      })
    },

    handleSelectionChange(item) {
      this.selectArr = item;
    },

    setRoleShow(rowData) {
      this.setRole = {
        roleIds: [],
        userId: rowData.row.userId
      };
      this.post({
        API: "roleList",
        data: {}
      }) .then(res => {
        this.roleListData = res;
      }) .catch(err => {
        this.$message.error(err);
      });

      // this.post({
      //   API: "setRoleList",
      //   data: {
      //     userId: rowData.row.userId
      //   }
      // }).then(res => {
      //   let arr = [];
      //   for (let i in res) {
      //     arr.push(res[i].roleId);
      //   }
      //   this.setRole.roleIds = arr;
      //   this.dialog = {
      //     title: "设置角色",
      //     show: true
      //   };
      // }).catch(err => {
      //   this.$message.error(err);
      // });

        this.dialog = {
          title: "设置角色",
          show: true
        };
    },

    setRoleSub() {
      // if (this.setRole.roleIds == "") {
      //   this.$message.error("请绑定角色");
      //   return false;
      // }
      this.btnLoading = true
      if(this.setRole.roleIds instanceof Array) {
        this.setRole.roleIds = this.setRole.roleIds.join(",");
      }

      this.post({
        API: "setRole",
        data: this.setRole
      }).then(res => {
        this.$message.success("设置成功");
        this.dialog.show = false;
        this.initData();
      }).catch(err => {
        this.$message.error(err);
      });
    },

    

    // 加载 列表
    initData() {
      
      let data = {
      };
      
      this.post({
        API: "pageList",
        data: data
      }).then(res => {
        this.tableData = res.data;
        this.tablePage = res.page;
      }) 
      .catch(err => {
        this.$message.error(err);
      });
    },
    editShow(row) {
      
      this.formGet({
        API: 'selectById',
        data: {
          id: row.row.userId
        }
      }).then(res => {
        res.seniorId = []
        res.subjectId = []
        res.siteId = []
        res.userSiteOuts.forEach(item => {
          switch (item.siteType) {
            case 1:
              res.seniorId.push(item.siteId)
              break;

            case 2:
              res.subjectId.push(item.siteId)
              break;
              
            case 3:
              res.siteId.push(item.siteId)
              break;
          
            default:
              break;
          }
        })
        
        // res.roleIds = res.roleIds.split(',');
        res.roleIds = res.siRoleOuts.map(e => { return e.roleId })

        this.addForm = res;

        this.dialog = {
          title: "编辑用户",
          show: true
        };

        

        // this.post({
        //   API: "setRoleList",
        //   data: {
        //     userId: row.row.userId
        //   }
        // }).then(res => {
        //   let arr = [];
        //   for (let i in res) {
        //     arr.push(res[i].roleId);
        //   }
        //   this.addForm.roleIds = arr;
        //   this.dialog = {
        //     title: "编辑用户",
        //     show: true
        //   };


          
        // }).catch(err => {
        //   this.$message.error(err);
        // });
      })

      
      
    },
    editSubmit() {

      this.$refs.addForm.validate((valid) => {
        if (valid) {
          this.btnLoading = true

          let data = JSON.parse(JSON.stringify(this.addForm))

          let siteEntityList = [];
          data.seniorId.forEach((item) => {
            let obj = {
              id: item,
              name: this.firstList.find(e => { return e.seniorId == item }).seniorName,
              siteType: 1
            }
            siteEntityList.push(obj)
          })
          data.subjectId.forEach((item) => {
            let obj = {
              id: item,
              name: this.mainList.find(e => { return e.subjectId == item }).subjectName,
              siteType: 2
            }
            siteEntityList.push(obj)
          })
          data.siteId.forEach((item) => {
            let obj = {
              id: item,
              name: this.secondList.find(e => { return e.siteId == item }).siteName,
              siteType: 3
            }
            siteEntityList.push(obj)
          })

          data.siteEntityList = siteEntityList;
          delete data.siteId
          

          if(data.roleIds instanceof Array) {
            data.roleIds = data.roleIds.join(",");
          }

          this.post({
            API: "edit",
            data: data
          }).then(res => {
            this.$message.success("编辑成功");
            this.dialog.show = false;
            this.initData();
          }).catch(err => {
            this.$message.error(err);
            this.btnLoading = false
          });
        }
      });
    },
    // 添加新账户
    addShow() {
      
      this.addForm = {
        // username: "",
        realname: "",
        gender: "",
        mobile: "",
        email: "",
        roleIds: [],
        password: "",
        passwordCopy: "",
        isAdmin: 0,
        userType: 2,
      }

      this.dialog = {
        title: "新增用户",
        show: true
      }
    },

    // encrypt(data, key) {
    //   var encrypted = this.$CryptoJS.AES.encrypt(data, this.$CryptoJS.enc.Utf8.parse(key), {
    //     mode: this.$CryptoJS.mode.ECB,
    //     padding: this.$CryptoJS.pad.Pkcs7,
    //   }).toString();

    //   return encrypted;
    // },
    addSubmit() {
      this.$refs.addForm.validate((valid) => {
        if (valid) {

          let data = JSON.parse(JSON.stringify(this.addForm))

          data.password = this.$encrypt(data.password, 'zhuxue6789xuezhu')
          data.passwordCopy = this.$encrypt(data.passwordCopy, 'zhuxue6789xuezhu')
          
          if(data.password !== data.passwordCopy) {
            this.$message.error('两次密码输入不一致');
            return false;
          }

          let siteEntityList = [];
          data.seniorId.forEach((item) => {
            let obj = {
              id: item,
              name: this.firstList.find(e => { return e.seniorId == item }).seniorName,
              siteType: 1
            }
            siteEntityList.push(obj)
          })
          data.subjectId.forEach((item) => {
            let obj = {
              id: item,
              name: this.mainList.find(e => { return e.subjectId == item }).subjectName,
              siteType: 2
            }
            siteEntityList.push(obj)
          })
          data.siteId.forEach((item) => {
            let obj = {
              id: item,
              name: this.secondList.find(e => { return e.siteId == item }).siteName,
              siteType: 3
            }
            siteEntityList.push(obj)
          })

          data.siteEntityList = siteEntityList;
          delete data.siteId
          

          if(data.roleIds instanceof Array) {
            data.roleIds = data.roleIds.join(",");
          }

          this.btnLoading = true
          this.post({
            API: "add",
            data: data
          })
            .then(res => {
              this.$message.success("新增成功");
              this.dialog.show = false;
              this.initData();
            })
            .catch(err => {
              this.$message.error(err);
              this.btnLoading = false
            });
          } else {
          return false;
        }
      });
    },
    deleteShow(row) {
      this.$confirm("是否确认删除", {
        confirmButtonText: "确 定",
        cancelButtonText: "取 消",
        type: "warning"
      }).then(() => {
        this.deleteSubmit(row);
      });
    },
    deleteSubmit(row) {
      this.btnLoading = true
      this.formGet({
        API: 'deleteById',
        data: {
          id: row.row.userId
        }
      }).then(res => {
        this.initData();
        this.$message.success('删除成功');
      }).catch(err => {
        this.$message.error(err);
        this.btnLoading = false
      })
    },

 

    handleSelectionChangeDelete(item) {
      for (let i = 0; i < item.length; i++) {
        if (item[i].isCreate == 1) {
          // 1 为管理员，不可移除
          this.adminCheck = true;
          break;
        } else {
          this.adminCheck = false;
        }
      }
      this.userIdArr = [];
      item.forEach(item => {
        this.userIdArr.push(item.userId);
      });
    },



    lockedFun(e) {
      if (e.row.locked == 0) {
        var bool = 1;
      } else {
        var bool = 0;
      }
      this.post({
        API: "locked",
        data: {
          locked: bool,
          userId: e.row.userId
        }
      })
        .then(res => {
          if (e.row.locked == 0) {
            this.$message.success("禁用成功");
          } else {
            this.$message.success("启用成功");
          }
          this.initData();
        })
        .catch(err => {
          this.$message.error(err);
        });
    },
    resetPassword(e) {
      this.$confirm("确认重置密码为“A123456”", {
        confirmButtonText: "确 定",
        cancelButtonText: "取 消",
        type: "warning"
      }).then(() => {
        this.formGet({
          API: "resetPassword",
          data: {
            userId: e.row.userId
          }
        })
          .then(res => {
            this.$message.success("密码重置成功");
          })
          .catch(err => {
            this.$message.error(err);
          });
      });
    },
  
    
    openDialog() {
      if(this.$refs.addForm) {
        this.$refs.addForm.resetFields();
      }
      this.btnLoading = false
    },
  },

  components: {
    materialTable,
    pagination,
    organizationStructure,
  }
}
</script>

<style scoped lang="less">

</style>